<template>
  <div class="custom-table" style="max-height: 18rem; overflow-y: auto;">
    <div
      class="easy-container-min flex align-items-center pointer"
      :class="selectedFolder.id ? '' : 'el-alert--success is-light'"
      @click="folderSelect"
    >
      <i class="cell f-normal shrink-0" :class="folderIcon"></i>
      <div class="line1">核心区</div>
    </div>
    <div v-show="folderOpened" class="p-l-16 custom-table">
      <folders-tree-item v-for="folder in children" :key="folder.id" :folder="folder" />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatResources } from '@/components/spaces/resources-v2/format';
import FoldersTreeItem from '@/components/shared/select-folder-dialog/folders-tree-item';

export default {
  name: 'select-folder-box',
  components: { FoldersTreeItem },
  props: {
    spaceId: {},
    selectedFolderId: {},
    isDisabled: Boolean,
  },
  data() {
    return {
      children: [],
      folderOpened: false,
      loading: false, // 正加载目录
    };
  },
  computed: {
    ...mapState(['selectedFolder']),
    folderIcon() {
      if (this.loading) return 'el-icon-loading';
      else if (this.folderOpened) return 'el-icon-folder-opened';
      return 'el-icon-folder';
    },
  },
  created() { this.loadRootFolders(); },
  destroyed() { this.setSelectedFolder(); },
  methods: {
    ...mapActions(['setSelectedFolder']),
    folderSelect() {
      this.folderOpened = !this.folderOpened;
      this.setSelectedFolder(); // 这里是清空为选中根目录
    },
    // 加载根目录
    loadRootFolders() {
      this.loading = true;
      this.$api.spaceResources.index({
        spaceId: this.spaceId,
        type: ['ProductFolder'],
      }).then((res) => {
        this.children = formatResources(res.data);
        this.folderSelect();
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    selectedFolder(val) {
      this.$emit('update:selectedFolderId', val.id);
    },
  },
};
</script>

<style></style>
